package logic

import (
	"context"
	"database/sql"
	"fmt"
	"goods/crud"
	"goods/es"
	"strconv"
	"time"

	"goods/goods"
	"goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateGoodLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateGoodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateGoodLogic {
	return &UpdateGoodLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func checkUpdate(in *goods.UpdateGoodRequest) error {
	if in.Info == nil {
		return fmt.Errorf("info is required")
	}

	if in.Info.ID == "" {
		return fmt.Errorf("id is required")
	}
	return nil
}

func (l *UpdateGoodLogic) updateGoodToMysql(in *goods.UpdateGoodRequest) error {
	id, err := strconv.Atoi(in.Info.ID)
	if err != nil {
		return err
	}

	goodMod := crud.NewGoodsModel(crud.Client)
	err = goodMod.Update(l.ctx, &crud.Goods{
		Id:      int64(id),
		Name:    in.Info.Name,
		Content: in.Info.Content,
		Price:   in.Info.Price,
		CreatedAt: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
		UpdatedAt: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
	})

	return err
}

func (l *UpdateGoodLogic) updateGoodToEs(in *goods.UpdateGoodRequest, id string) error {
	return es.SaveData(id, "good", in.Info)
}

func (l *UpdateGoodLogic) UpdateGood(in *goods.UpdateGoodRequest) (*goods.UpdateGoodResponse, error) {
	err := checkUpdate(in)
	if err != nil {
		return nil, err
	}

	err = l.updateGoodToMysql(in)
	if err != nil {
		return nil, err
	}

	err = l.updateGoodToEs(in, in.Info.ID)
	if err != nil {
		return nil, err
	}

	return &goods.UpdateGoodResponse{
		Info: &goods.Good{
			ID:      in.Info.ID,
			Name:    in.Info.Name,
			Content: in.Info.Content,
			Price:   in.Info.Price,
		},
	}, nil
}
